//
//  Common.m
//  TAOVideo
//
//  Created by Lin Eidan on 13-8-6.
//  Copyright (c) 2013年 taomee. All rights reserved.
//

#import "config.h"
#import "Header.h"
//#import "OpenUDID.h"
#import <CommonCrypto/CommonDigest.h>
#import <AVFoundation/AVFoundation.h>
#import "BaseViewController.h"

@implementation Common


+(CGFloat)degreesToRadians:(CGFloat )degrees{
    return degrees * M_PI / 180;
}

+(CGFloat)radiansToDegrees:(CGFloat )radians{
    return radians * 180 / M_PI;
}


+ (NSString *)md5:(NSString *)str{
    const char *original_str = [str UTF8String];
    unsigned char result[16];
    CC_MD5(original_str, (CC_LONG)strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++) {
        [hash appendFormat:@"%02X", result[i]];
    }
    return [hash lowercaseString];
}

//不管是否设置了静音，播放器都会有声音，无视静音键。
+(void)handleAlwaysSoundIgnoreMuteSwitch{
    NSError *error = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
}


//————————————系统相关 start———————————

// 获取IOS系统的版本号
+ (NSString*)getOSVersion{
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)getOpenUDID{
//    return [OpenUDID value];
    return @"";
}

+(NSString *)getAppBundleId{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
}

+ (NSString *)getAppVersion{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];//version
}
+ (NSString *)getAppBuild{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
}
+ (NSString *)getAppVersionInfo{
    return [NSString stringWithFormat:@"%@(build_%@)",[Common getAppVersion],[Common getAppBuild]];
}

+ (BOOL)isIPad{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return NO;
    }else if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
        return YES;
    }
    return NO;
}

+(NSString *)getAppStoreURL{
    NSString *urlStr = [NSString stringWithFormat:@"https://itunes.apple.com/app/id%@", AppleAppID];
    return urlStr;
}

+(void)goToAppStore{
    NSURL *url = [NSURL URLWithString:[Common getAppStoreURL]];
    [[UIApplication sharedApplication] openURL:url];
}

//————————————系统相关 end———————————

+(NSString *)getARadomPhoneNum{
    NSString *phone =@"";
    NSArray *second = @[@"3",@"5",@"8"];
    NSArray *third = @[@"0",@"2",@"5",@"6",@"7",@"8",@"9"];
    phone = [NSString stringWithFormat:@"1%@%@****%d",[second objectAtIndex:[self getRandomNumber:0 to:2]],[third objectAtIndex:[self getRandomNumber:0 to:6]],[self getRandomNumber:1000 to:9999]];
    return phone;
}

+(NSString *)getARadomQQNum{
    NSString *qq = [NSString stringWithFormat:@"%d****",[Common getRandomNumber:100 to:999999]];
    return qq;
}


//获取随机数
+(int)getRandomNumber:(int)from to:(int)to{
    return (int)(from + (arc4random() % (to - from + 1)));
}


+ (UIImage *)createImageWithColor:(UIColor *)color
{
    return [self createImageWithColor:color andSize:CGSizeMake(1, 1)];
}

+ (UIImage *)createImageWithColor:(UIColor *)color andSize:(CGSize )size
{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

//根据一个url，这个url包含了一长串路径名和后缀名，函数的作用是获取真正的文件名，不含路径和后缀。。
+(NSString *)getTrueDocName:(NSURL *)path{
    NSString *pathString=[path path];
    if ([pathString rangeOfString:@"/" options:NSBackwardsSearch].location == NSNotFound) {
        return nil;
    }
    int location= (int)[pathString rangeOfString:@"/" options:NSBackwardsSearch].location;
    NSString *docName=[pathString substringFromIndex:location+1];
    location=(int)[docName rangeOfString:[path pathExtension]].location;
    docName=[docName substringToIndex:location-1];
    return docName;
}

//根据一个文件的路径名，获得其所在的文件夹的路径
+(NSString *)getFolderOfTheFile:(NSString *)pathString{
    if ([pathString rangeOfString:@"/" options:NSBackwardsSearch].location == NSNotFound) {
        return nil;
    }
    int location=(int)[pathString rangeOfString:@"/" options:NSBackwardsSearch].location;
    NSString *folderPath=[pathString substringToIndex:location];
    return folderPath;
}

//获取一个带“／”的字符串，“／”后面的字符串
+(NSString *)getLastStringFromSlash:(NSString *)pathString{
    if ([pathString rangeOfString:@"/" options:NSBackwardsSearch].location == NSNotFound) {
        return nil;
    }
    int location=(int)[pathString rangeOfString:@"/" options:NSBackwardsSearch].location;
    NSString *folderPath=[pathString substringFromIndex:location+1];
    return folderPath;
}

//去除两端空格
+(NSString *)removeCharacterSpace:(NSString *)str{
    NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return temp;
}

//去除两端空格和回车
+(NSString *)removeCharacterSpaceAndEnter:(NSString *)str{
    NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return temp;
}

//中文转化为UTF8，这样才能用于URL。
+ (NSString *)convertStringToUTF8:(NSString *)str{
    NSString * content = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge_retained CFStringRef)str, NULL, NULL, kCFStringEncodingUTF8);
    return content;
}

+(void)handleHeightWithIPhone5WithView:(UIView *)view{
    float defaultValue=460;
    if (isiOS7) {
        defaultValue=480;
    }
    view.height = defaultValue + (isiPhone5 ? 88:0);
}

+(void)handleWidthWithIPhone5WithView:(UIView *)view{
    float defaultValue=460;
    if (isiOS7) {
        defaultValue=480;
    }
    view.width = defaultValue + (isiPhone5 ? 88:0);
}

+(void)handleRightSizeWithPadLandscapeAndPhonePortraitWithView:(UIView *)view{
    float width = 1024;
    float height = 768;
    if (!isPad) {
        width = 320;
        height = 568;
        if (!isiPhone5) {
            height = 480;
        }
    }
    view.width = width;
    view.height = height;
}

//对view设置“变换”和frame，常用于强制旋转后的归位。
+(void)handleView:(UIView *)view withFrame:(CGRect )frame andTransform:(CGAffineTransform)transform{
    view.transform = transform;
    view.frame = frame;
}

+(void)networkActivityIndicatorDisplay:(BOOL)isDisplay{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:isDisplay];
}

//ios6下，位置还取决于状态栏是否隐藏，状态栏显示的话 ，就要－20.
+(void)handleTheViewTopDependOnStatusBarInIOS6:(UIView *)view{
    BOOL hidden = [UIApplication sharedApplication].statusBarHidden;
    view.top = isiOS7 ? 0 : (hidden ? 0 : -20);   //ios6下，位置还取决于状态栏是否隐藏，状态栏显示的话 ，就要－20.
}

//ios7状态栏背景色
+(UIView *)handleTheStateBarWithBackgroundColor:(UIColor *)color andAlpha:(float) alpha InTheView:(UIView *)parentView{
    if (isiOS7) {
        UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, parentView.width, 20)];
        blueView.backgroundColor = color;
        blueView.alpha = alpha;
        [parentView addSubview:blueView];
        return blueView;
    }
    return nil;
}

//ios7不好使
+(void)handleTheStatusBarDislay:(BOOL )isDislay{
    UIApplication *myApp = [UIApplication sharedApplication];
    [myApp setStatusBarHidden:!isDislay withAnimation:UIStatusBarAnimationFade];
}

+(void)handleStatusBarTo:(UIInterfaceOrientation)orientation {
    [self handleStatusBarTo:orientation withAnimation:NO];
}

+(void)handleStatusBarTo:(UIInterfaceOrientation)orientation withAnimation:(BOOL)isAnimation{
    [[UIApplication sharedApplication] setStatusBarOrientation:orientation animated:isAnimation];
}


+(void)putTheView:(UIView *)view inHorizontalCenterOfParentView:(UIView *)parentView{
    view.left=(parentView.width-view.width)/2;
}

+(UIInterfaceOrientation)getCurrentStatusBarOri{
    UIInterfaceOrientation orientationOrigin = [UIApplication sharedApplication].statusBarOrientation;
    return orientationOrigin;
}

//播放视频，强制横屏
+(void)forcedTheView:(UIView *)view toTheOrientaion:(UIInterfaceOrientation)orientation{
    UIInterfaceOrientation orientationOrigin = [UIApplication sharedApplication].statusBarOrientation;
    if (orientation == orientationOrigin) {
        return;
    }
    [self handleStatusBarTo:orientation];
    CGAffineTransform transform;
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        if (orientationOrigin == UIInterfaceOrientationPortrait) {
            transform = CGAffineTransformMakeRotation(M_PI/2);
        }else if (orientationOrigin == UIInterfaceOrientationPortraitUpsideDown){
            transform = CGAffineTransformMakeRotation(-M_PI/2);
        }
        
    }else if (orientation == UIInterfaceOrientationPortrait){
        if (orientationOrigin == UIInterfaceOrientationLandscapeRight) {
            transform = CGAffineTransformMakeRotation(0);
        }else if (orientationOrigin == UIInterfaceOrientationLandscapeLeft){
            transform = CGAffineTransformMakeRotation(M_PI/2);
        }
    }
    view.transform=transform;
    
}

//视频播放，pushview。
+(void)pushViewWithAnimation:(UIView *)view withParentView:(UIView *)parentView{
    view.left=0.0;
    view.top=parentView.height;
    [parentView addSubview:view];
    [UIView animateWithDuration:0.3 animations:^{
        view.top=0.0;
    }];
}

//视频播放popview。
+(void)popViewWithAnimation:(UIView *)view{
    [self handleStatusBarTo:UIInterfaceOrientationPortrait];
    
    [UIView animateWithDuration:0.3 animations:^{
        view.top=view.height+(isiOS7 ? 20:0);
    } completion:^(BOOL finished) {
        [view removeFromSuperview];
    }];
    
}

//处理时间变成00:00:00格式
+(NSString *)handleTheTime:(float )interval{
    int hour=0;
    int minute=0;
    int second=0;
    
    div_t h =div(interval, 3600);
    hour=h.quot;
    div_t m=div(h.rem, 60);
    minute=m.quot;
    second=m.rem;
    NSString *hourString,*minString,*secString;
    
    if (hour < 10) {
        hourString = [NSString stringWithFormat:@"0%d",hour];
    }else{
        hourString = [NSString stringWithFormat:@"%d",hour];
    }
    
    if (minute < 10) {
        minString = [NSString stringWithFormat:@"0%d",minute];
    }else{
        minString = [NSString stringWithFormat:@"%d",minute];
    }
    
    if (second < 10) {
        secString = [NSString stringWithFormat:@"0%d",second];
    }else{
        secString = [NSString stringWithFormat:@"%d",second];
    }
    
    NSString *all=[NSString stringWithFormat:@"%@:%@:%@",hourString,minString,secString];
    return all;
    
}




//create Label
+(UILabel *)createLabelWithFrame:(CGRect )frame andText:(NSString *)text andTextColor:(UIColor *)color andFontSize:(int )fontSize andTextAlignment:(NSTextAlignment )textAlignment{
    UILabel *label=[[UILabel alloc] initWithFrame:frame];
    label.text=text;
    label.textColor = color;
    label.textAlignment = textAlignment;
    label.font=[UIFont fontWithName:@"Helvetica Neue" size:fontSize];
    label.backgroundColor = [UIColor clearColor];
    return label;
}

//根据字符串的多少，对特定label的宽度，进行适配，让label的高度刚刚好。
+(float )handleTheLabelHeight:(UILabel *)label withText:(NSString *)str withMaxHeight:(float )maxHeight{
    label.text = str;
    float height = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.width, maxHeight)].height;
    
    label.height = height;
    return height;
}

+(float)handleTheLabelWidth:(UILabel *)label withText:(NSString *)str
{
    label.text = str;
    float width = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.width, label.height)].width;
    label.width = width+5;
    return width;
}

+(float)handleTheLabelHeight:(UILabel *)label withText:(NSString *)str
{
    label.text = str;
    float height = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.width, label.height)].height;
    label.height = height;
    return height;
}

+ (float)heightForString:(UILabel *)textViewLabel{
    float tempHeight=textViewLabel.height;
    textViewLabel.height=1000;
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:textViewLabel.text];
    NSRange range = NSMakeRange(0, attrStr.length);
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];   // 获取该段attributedString的属性字典
    
    CGSize textSize;
    if (isiOS7) {
        textSize = [textViewLabel.text boundingRectWithSize:textViewLabel.bounds.size // 用于计算文本绘制时占据的矩形块
                                                    options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                                 attributes:dic        // 文字的属性
                                                    context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    }else{
        textSize = [attrStr boundingRectWithSize:textViewLabel.bounds.size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    }
    textViewLabel.height=tempHeight;
    return textSize.height;
}

//时间相关

//获得今天日期的具体信息。
+ (NSDateComponents *)getDateDetailInfo{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit ;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    return comps;
}

//获得今天几号。
+ (int)getTodayDate{
    NSDateComponents *dateComps = [self getDateDetailInfo];
    return (int)dateComps.day;
}

//获得今天星期几。
+ (int )getTodayWeekDay{
    NSDateComponents *dateComps = [self getDateDetailInfo];
    return (int)dateComps.weekday;
}

//在scrollView中有合适的位置。上下拉，不超出边界。
+(float )handleTheOffsetY:(float) offset toRightInScrollView:(UIScrollView *)scrollView{
    if (offset > scrollView.contentHeight - scrollView.height) {
        offset = scrollView.contentHeight - scrollView.height;
    }else if (offset < 0){
        offset = 0;
    }
    return offset;
}

//左右滑,不超出边界。
+(float )handleTheOffsetX:(float) offset toRightInScrollView:(UIScrollView *)scrollView{
    if (offset < 0) {
        offset = 0;
        
    }else if (offset > scrollView.contentWidth -scrollView.width){
        offset = scrollView.contentWidth - scrollView.width;
    }
    return offset;
}

//让一个在scrollView视图中的view，一开始跟着滑动，然后他快要消失的时候就顶着scrollView的边，不消失，然后回退的时候，他又回到原来的位置，类似tableView的每个section的headerView的效果。
+(void)handleView:(UIView *)subView andThisViewDefaultY:(float)defaultY InScrollViewAlwaysCanSee:(UIScrollView *)scrollView{
    if (scrollView.contentOffsetTop > defaultY) {
        subView.top = scrollView.contentOffsetTop;
    }else{
        subView.top = defaultY;
    }
}

//tableview的组视图跟着滑
+(void)tableHeaderScrollWithScrollView:(UIScrollView *)scrollView andWithHeaderHeight:(CGFloat)sectionHeaderHeight
{
    if (scrollView.contentOffset.y<=sectionHeaderHeight && scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);//上，左，下，右
    }else if (scrollView.contentOffset.y >= sectionHeaderHeight){
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }

}

//加分
+(void)addScoreWithParentView:(UIView *)parentView
{
    UIImageView* scoreImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 25, 23)];
    scoreImageView.image = [UIImage imageNamed:@"increase"];
    
    scoreImageView.left = (parentView.width-scoreImageView.width)/2;
    scoreImageView.top = (parentView.height-scoreImageView.height)/2;
    
    [parentView addSubview:scoreImageView];
    [UIView animateWithDuration:1 animations:^{
        scoreImageView.alpha = 0;
        scoreImageView.top -= 20;
        scoreImageView.transform = CGAffineTransformScale(scoreImageView.transform, 2, 2);
    } completion:^(BOOL finished) {
        [scoreImageView removeFromSuperview];
    }];
}

//检测越狱
+ (BOOL)isJailBreak{
    int res = system("ls");
    if (res == 0){
        return YES;
    }else{
        return NO;
    }
}

+(BOOL)isJailBroken{
    NSArray *apps = @[@"/Applications/Cydia.app",@"/Applications/limera1n.app",@"/Applications/greenpois0n.app",@"/Applications/blackra1n.app",@"/Applications/blacksn0w.app",@"/Applications/redsn0w.app"];
    for(int i =0; i< apps.count ;i++){
        if([[NSFileManager defaultManager] fileExistsAtPath :[Common convertStringToUTF8:[apps objectAtIndex:i]]]){
            return YES;
        }
    }
    return NO;
}

//今天是否需要去请求数据,后面的函数是间隔几天。4号请求过了，想5号就去请求，参数就为1，想6号请求，就是2，想7号请求就是3
+(BOOL)todayNeedToNewDataOrNotForKey:(NSString *)dataKey everyFewDays:(int )day{
    BOOL need = NO;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([userDefaults integerForKey:dataKey]) {
        int todayDate = [Common getTodayDate];
        int lastDate = [userDefaults integerForKey:dataKey];
        if (lastDate > todayDate || todayDate >= lastDate + day) {
            need = YES;
        }
    }else{  //如果重来都没有存过，那么就是没有取到过，需要去取。
        need = YES;
    }
    return need;
}

//今天已经取得了最新数据。。
+(void)todayHasGetNewDataForKey:(NSString *)dataKey{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    int day = [Common getTodayDate];
    [userDefaults setInteger:day forKey:dataKey];
    [userDefaults synchronize];
}


#pragma mark - 获取上一次保存的最大信息id
+(NSString*)getMaxMesgId
{
    if(![UserDataBasic getObjectForKey:LocalSystemMaxId])
    {
        return @"1";
    }
    else{
        return [UserDataBasic getObjectForKey:LocalSystemMaxId];
    }
}

+(BOOL)checkPhoneLegal:(NSString *)phone{
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    BOOL res1 = [regextestmobile evaluateWithObject:phone];
    BOOL res2 = [regextestcm evaluateWithObject:phone];
    BOOL res3 = [regextestcu evaluateWithObject:phone];
    BOOL res4 = [regextestct evaluateWithObject:phone];
    
    if (res1 || res2 || res3 || res4 ){
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - 添加小红点
+(void)addRedCircleForView:(UIView *)mView andPosition:(CGRect)position andCounts:(int)nums
{
    UIView* bgView = [[UIView alloc]initWithFrame:position];
    bgView.tag = 10000;
    UIImageView* imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ellipse.png"]];
    imageView.frame = bgView.bounds;
    
    UILabel* label = [[UILabel alloc]initWithFrame:bgView.bounds];
    label.text = [NSString stringWithFormat:@"%d",nums];
    label.font = [UIFont systemFontOfSize:8];
    label.textColor = RGB(245, 245, 245);
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    
    [bgView addSubview:imageView];
    [bgView addSubview:label];
    
    if(nums>0)
    {
        [mView addSubview:bgView];
    }
}

#pragma mark - 点击获得文耀
+(void)getWYByPostWithType:(NSString *)type andItemId:(NSString *)ItemId
{
    NSString* url = [NSString stringWithFormat:@"%@dealUserAction",API_BASE];
    NSString* uid = [[UserObj sharedInstance] uid];
    NSString* ak = [[UserObj sharedInstance] accessKey];
    
    if(!IsNull(uid)&&!IsNull(ak))
    {
        [[AFGetData sharedInstance] startPost:url andInfo:@{@"uid": uid,@"ak":ak,@"type":type,@"id":ItemId} andDataBodyBlock:^(id<AFMultipartFormData> formData) {
        } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
            NSLog(@"res = %@",responseObj);
        }];
        
        
    }
}

@end
